package com.gexin.service.memberAcitivty;

import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.BigDecimalUtils;
import com.gexin.common.utils.UUIDUtils;
import com.gexin.model.activity.*;
import com.gexin.model.enums.MemberInfoEnum;
import com.gexin.model.enums.MemberOrderItergralStatusEnum;
import com.gexin.model.order.Order;
import com.gexin.model.order.OrderItem;
import com.gexin.model.product.Products;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


public class IntegralService {

    private static final MemberActivityService memberActivityService = new MemberActivityService();

    private static final Logger LOG = Logger.getLogger(IntegralService.class);

    public ApiResponse getCoinCount(String userId) {
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(userId);
        BigDecimal coinCount = BigDecimal.ZERO;
        if (memberBillSpeedIntegral != null) {
            coinCount = memberBillSpeedIntegral.getCoinCount();
        }
        return new ApiResponse(false, "返回成功", coinCount);
    }


    /**
     * 待确认收货状态
     *
     * @param order
     * @param userId
     */
    public void confirmDelivery(Order order, String userId) {
        LOG.info("待确认收货状态,增加兑货券" + order.getId());
        MemberOrder byOrderId = MemberOrder.dao.findByOrderId(order.getId());
        if (byOrderId != null) {
            return;
        }
        BigDecimal multiRule = memberActivityService.getGarde(order.getUserId() + "");
//      活动订单详情表
        List<Products> allProductsList = Products.dao.findAll();
        Map<Integer, Products> allProductsMap = allProductsList.stream().filter(products -> products.getId() != null).
                collect(Collectors.toMap(Products::getId, a -> a, (k1, k2) -> k1));
        List<MemberOrderIntegral> memberOrderIntegralList = MemberOrderIntegral.dao.getMemberOrderList();
        BigDecimal forcastIntegralSum = BigDecimal.ZERO;
        BigDecimal allProductIntegralsum = BigDecimal.ZERO;
        List<OrderItem> orderItemList = OrderItem.dao.findOrderItemByOrderId(order.getId() + "");
        MemberInfo memberInfo = MemberInfo.dao.getMemberInfoByUserId(userId);
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(userId + "");
//      设置个人积分表(为了之前维护)
        if (memberInfo == null) {
            memberInfo = new MemberInfo();
            memberInfo.setMemberInfo(UUIDUtils.getUUIDInOrderId() + "", userId, 0, null);
            memberInfo.save();
        }
        if (memberBillSpeedIntegral == null) {
            memberBillSpeedIntegral = new MemberBillSpeedIntegral();
            memberBillSpeedIntegral.setUserIdAndSpeedIntegralAndCoinAndBillCouponAndForecastAndRemainAndReverseAndDailyIncrement(
                    userId, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                    BigDecimal.ZERO);
            memberBillSpeedIntegral.save();
        }
        int level = memberInfo.getLevel() == null ? 0 : memberInfo.getLevel();
        BigDecimal vistorIntegral = BigDecimal.ZERO;
        for (int i = 0; i < orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            Integer itemId = orderItem.getItemId();
            if (itemId == null) {
                continue;
            }
//          不应该存在这一部
            Optional<MemberOrderIntegral> memberOrderIntegralOperational = memberOrderIntegralList.stream().
                    filter(memberOrderIntegral -> memberOrderIntegral.getOrderItemId() != null
                    && memberOrderIntegral.getOrderItemId().equals(itemId + "")).findFirst();
            if (memberOrderIntegralOperational.isPresent()) {
                continue;
            }
            Integer productId = orderItem.getProductId();
            if (productId == null) {
                continue;
            }
            Products product = allProductsMap.get(productId);
            if (product == null) {
                continue;
            }
            BigDecimal magnification = product.getMagnification() == null ? BigDecimal.ZERO : product.getMagnification();
            if (BigDecimalUtils.equal(magnification, BigDecimal.ZERO)) {
                magnification = new BigDecimal("1");
            }
//          某一产品个数总和
            int nums = orderItem.getNums() == null ? 0 : orderItem.getNums();
            int integral = product.getIntegral() == null ? 0 : product.getIntegral();
            int orderItemIntegralSum = nums * integral;
            vistorIntegral = vistorIntegral.add(BigDecimal.valueOf(orderItemIntegralSum));
            BigDecimal orderIntegral = BigDecimal.valueOf(orderItemIntegralSum).multiply(magnification);
            if (level == MemberInfoEnum.SECOND_LEVEL.getCode() || level == MemberInfoEnum.THIRD_LEVEL.getCode()) {
                MemberOrderIntegral memberOrderIntegral = new MemberOrderIntegral();
                memberOrderIntegral.setUserIdAndBillAndItemIdAndStatus(UUIDUtils.getUUIDInOrderId() + "", userId, orderIntegral,
                        orderItem.getItemId() + "", magnification, MemberOrderItergralStatusEnum.BERECEIVED.getCode());
                memberOrderIntegral.save();
                allProductIntegralsum = allProductIntegralsum.add(orderIntegral);
            }
        }
//      应该合并成一张表
        if (level != MemberInfoEnum.SECOND_LEVEL.getCode() && level != MemberInfoEnum.THIRD_LEVEL.getCode()) {
            LOG.info("普通用户" + level);
            VistorOrder vistorOrder = new VistorOrder();
            vistorOrder.setCommonConditionalOrderIdAndIntegralAndIncomeOrAndTypeAndDesc(
                    order.getId(), vistorIntegral, 1, 1, "买商品获得积分");
            vistorOrder.setStatus(MemberOrderItergralStatusEnum.BERECEIVED.getCode());
            vistorOrder.save();
        } else {
//          预计可获得积分
            LOG.info("会员" + order.getId());
            BigDecimal orderIntegral = allProductIntegralsum.multiply(multiRule);
            forcastIntegralSum = forcastIntegralSum.add(orderIntegral);
            MemberOrder memberOrder = new MemberOrder();
            memberOrder.setOrderIdAndBillIntegralAndAcquireAndDailyIncrementAndForecastIntegralAndRemainIntegralAndMultiRuleAndStatus(
                    order.getId(), allProductIntegralsum, BigDecimal.ZERO, BigDecimal.ZERO, forcastIntegralSum, BigDecimal.ZERO, multiRule,
                    MemberOrderItergralStatusEnum.BERECEIVED.getCode());
            memberOrder.save();
            BigDecimal forecastSpeedIntegral = memberBillSpeedIntegral.getForecastSpeedIntegral();
            forecastSpeedIntegral = forecastSpeedIntegral.add(forcastIntegralSum);
            memberBillSpeedIntegral.setForecastSpeedIntegral(forecastSpeedIntegral);
            memberBillSpeedIntegral.setUpdateTime(new Date().getTime());
            memberBillSpeedIntegral.update();
        }

    }

    /**
     * @param order 已完成的所有订单并且参与了活动的订单
     * @return
     */
    public List<Order> commonCondition(Order order) {
//        List<MemberOrder> MemberOrderCollect = MemberOrder.dao.findAll();
        List<VistorOrder> vistorOrderList = VistorOrder.dao.findAll();
        Map<String, VistorOrder> vistorOrderMap = vistorOrderList.stream().filter(MemberOrder -> MemberOrder
                .getOrderId() != null).collect(Collectors.toMap(VistorOrder::getOrderId, a -> a, (k1, k2) -> k1));
//      找到该用户下边所有已完成的用户列表
        Integer userId = order.getUserId();
        if (userId == null) {
            return null;
        }
        List<Order> orderList = Order.dao.getOrderListByUserIdAndStatus(3, userId + "");
        List<Order> collect = orderList.stream().filter(orderStream -> vistorOrderMap.
                containsKey(orderStream.getId())).collect(Collectors.toList());
        return collect;
    }

    /**
     * 用来判断是否升级为会员
     *
     * @param order
     * @param
     */
    public void memberExchage(Order order) {
        MemberLevel memberLevel = MemberLevel.dao.getMemberLevel(MemberInfoEnum.SECOND_LEVEL.getCode());
        if (memberLevel == null) {
            return;
        }
        List<Order> alreadyOrder = commonCondition(order);
        BigDecimal sum = alreadyOrder.stream().filter(orderStream -> orderStream.getTotalAmount() != null)
                .map(Order::getTotalAmount) .reduce(BigDecimal.ZERO,BigDecimal::add);
//      加上本次的
        BigDecimal totalAmount = order.getTotalAmount() == null ? BigDecimal.ZERO : order.getTotalAmount();
        BigDecimal togetherSum = sum.add(totalAmount);
//      把每一笔order的价钱放到一个表里，判断是否大于1500
        BigDecimal standard = memberLevel.getStandard() == null ? BigDecimal.ZERO : memberLevel.getStandard();
        LOG.info("sum:"+sum+"__________standard:"+standard+"__________togetherSum:"+togetherSum);
        if (standard != null && BigDecimalUtils.lessThan(sum, standard) &&
                BigDecimalUtils.greaterEqual(togetherSum, standard)) {
            MemberInfo memberInfo = MemberInfo.dao.getMemberInfoByUserId(order.getUserId() + "");
            memberInfo.setLevel(MemberInfoEnum.SECOND_LEVEL.getCode());
            memberInfo.setRemind(1);
            memberInfo.update();
        }
    }


    /**
     * 用戶确认收货,修改状态(积分的)
     *
     * @param
     * @param
     * @param
     */
    public void buyGeneralIntegral(Order order) {
        String userId = order.getUserId() + "";
        if (StringUtils.isBlank(userId)) {
            return;
        }
        MemberInfo memberInfo = MemberInfo.dao.getMemberInfoByUserId(userId);
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.
                getMemberBillSpeedIntegralByUserId(userId);
//      判断用户是否为空(前期账户可能没有信息...购买完商品可能要增加的,也就这几天的,加上)
        if (null == memberInfo) {
            String id = UUID.randomUUID() + "";
            memberInfo = new MemberInfo();
            memberInfo.setMemberInfo(id, userId, 0, "0");
            memberInfo.save();
            return;
        }
//      其实不需要这东西的在创建的时候就有了,也就这几天要用到
        BigDecimal forcastIntegral = BigDecimal.ZERO;
        BigDecimal multiRule = BigDecimal.ZERO;
        if (memberBillSpeedIntegral == null) {
            memberBillSpeedIntegral = new MemberBillSpeedIntegral();
            memberBillSpeedIntegral.setUserIdAndSpeedIntegralAndCoinAndBillCouponAndForecastAndRemainAndReverseAndDailyIncrement(
                    userId, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, forcastIntegral, forcastIntegral,
                    multiRule, BigDecimal.ZERO);
            memberBillSpeedIntegral.save();
        }
//      升级会员(根据积分表消费总额)
        memberExchage(order);
//      确认收货修改释放比例以及状态
        if (memberInfo.getLevel() == MemberInfoEnum.SECOND_LEVEL.getCode() || memberInfo.getLevel() == MemberInfoEnum.THIRD_LEVEL.getCode()) {
            MemberOrder memberOrder = MemberOrder.dao.findByOrderId(order.getId());
            if (memberOrder == null) {
                return;
            }
//          更改的话已经得到了预计可获得需要减掉
            multiRule = memberActivityService.getGarde(order.getUserId() + "");
            BigDecimal memberOrderForcastIntegral = multiRule.multiply(memberOrder.getBillIntegral());
            BigDecimal forecastSpeedIntegral = memberBillSpeedIntegral.getForecastSpeedIntegral();
            if (BigDecimalUtils.greaterThan(memberOrderForcastIntegral, memberOrder.getForecastIntegral())) {
                BigDecimal memberOrderCurrentIncrement = BigDecimal.ZERO;
                memberOrderCurrentIncrement = memberOrderForcastIntegral.subtract(memberOrder.getForecastIntegral());
                forecastSpeedIntegral = forecastSpeedIntegral.add(memberOrderCurrentIncrement);
                memberBillSpeedIntegral.setForecastSpeedIntegral(forecastSpeedIntegral);
                memberBillSpeedIntegral.setReverse(multiRule);
            }
            BigDecimal remainSpeedIntegral = memberBillSpeedIntegral.getRemainSpeedIntegral();
            remainSpeedIntegral = remainSpeedIntegral.add(memberOrderForcastIntegral);
            memberBillSpeedIntegral.setRemainSpeedIntegral(remainSpeedIntegral);
            memberBillSpeedIntegral.update();

            memberOrder.setAcquiredIntegralAndForcastIntegralAndDailyIncrementAndRemainIntegralAndStatus(
                    BigDecimal.ZERO, BigDecimal.ZERO, memberOrderForcastIntegral, memberOrderForcastIntegral,
                    multiRule, MemberOrderItergralStatusEnum.CONFIRM_THE_RECEIVE.getCode());
            memberOrder.update();

//          签到直荐,拼团多出来的要给新确认收货的订单补上
            BigDecimal freezeIntegral = memberBillSpeedIntegral.getFreezeIntegral();
            if (freezeIntegral != null && !BigDecimalUtils.equal(freezeIntegral, BigDecimal.ZERO)) {
                MemberActivityService memberActivityService = new MemberActivityService();
                freezeIntegral = memberActivityService.recurrentTask(multiRule, memberOrder,
                        freezeIntegral, null);
                memberBillSpeedIntegral.setFreezeIntegral(freezeIntegral);
                memberBillSpeedIntegral.update();
            }
        } else {
            VistorOrder vistorOrder = new VistorOrder().dao().getVistorOrder(order.getId());
            if (vistorOrder == null) return;
            BigDecimal integral = vistorOrder.getIntegral();
            vistorOrder.setStatus(2);
            vistorOrder.update();
            BigDecimal normalIntegral = memberBillSpeedIntegral.getNormalIntegral() == null ? BigDecimal.ZERO : memberBillSpeedIntegral.getNormalIntegral();
            normalIntegral = normalIntegral.add(integral);
            memberBillSpeedIntegral.setNormalIntegral(normalIntegral);
            memberBillSpeedIntegral.setUpdateTime(new Date().getTime());
            memberBillSpeedIntegral.update();
        }
    }


    public ApiResponse checkTobeMember(String userId) {
        MemberInfo memberInfo = MemberInfo.dao.getMemberInfoByUserId(userId);
        if (memberInfo != null && memberInfo.getLevel() != 1 && memberInfo.getRemind() != null
                && memberInfo.getRemind() == 1) {
            Integer level = memberInfo.getLevel();
            String value = MemberInfoEnum.getValue(level);
            if (value != null) {
                memberInfo.setRemind(0);
                memberInfo.update();
                Map map = new HashMap();
                map.put("msg", "您已成为" + value);
                return new ApiResponse(true, "返回成功", map);
            }
        }
        return new ApiResponse(true, "返回成功");
    }


    public void memberExchageRemind(Order order, BigDecimal activityOrderListSum) {
//      本次要完成活动的订单
        String orderId = order.getId();
        MemberOrder memberOrder = MemberOrder.dao.findByOrderId(orderId);
        if (memberOrder != null && 0 == memberOrder.getStatus()) {
            BigDecimal currentOrderTotalAmount = activityOrderListSum.add(order.getTotalAmount());
//          会员级别表(粉客,推广者都要提醒功能)
            List<MemberLevel> memberLevelList = MemberLevel.dao.findAll();
            for (int i = 0; i < memberLevelList.size(); i++) {
                MemberLevel memberLevel = memberLevelList.get(i);
                BigDecimal standard = memberLevel.getStandard() == null ? BigDecimal.ZERO : memberLevel.getStandard();
                if (BigDecimalUtils.lessThan(activityOrderListSum, standard) &&
                        BigDecimalUtils.greaterEqual(currentOrderTotalAmount, standard)) {
                    MemberInfo memberInfo = MemberInfo.dao.getMemberInfoByUserId(order.getUserId() + "");
                    memberInfo.setLevel(memberLevel.getLevel());
                    memberInfo.setRemind(1);
                    memberInfo.update();
                }
            }
        }
    }


    /**
     * 退款取消当前用户的积分
     */
    public void reimburse(Order order) {
        Integer userId = order.getUserId();
        if (userId == null) {
            return;
        }
        MemberInfo memberInfoByUserId = MemberInfo.dao.getMemberInfoByUserId(userId + "");
        if (memberInfoByUserId == null) {
            return;
        }
        String orderId = order.getId() + "";
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(userId + "");
        if(memberBillSpeedIntegral==null){
            return;
        }
        if (!memberInfoByUserId.getLevel().equals(MemberInfoEnum.THIRD_LEVEL.getCode()) &&
                !memberInfoByUserId.getLevel().equals(MemberInfoEnum.SECOND_LEVEL.getCode())) {
            VistorOrder vistorOrder = VistorOrder.dao.getVistorOrder(orderId);
            if(vistorOrder==null){
                return;
            }
            vistorOrder.setStatus(4);
            BigDecimal integral = vistorOrder.getIntegral();
            BigDecimal normalIntegral = memberBillSpeedIntegral.getNormalIntegral();
            normalIntegral = normalIntegral.subtract(integral);
            memberBillSpeedIntegral.setNormalIntegral(normalIntegral);
        } else {
            MemberOrder memberOrder = MemberOrder.dao.findByOrderId(orderId);
            if (memberOrder == null) {
                return;
            }
            memberOrder.setStatus(4);
            BigDecimal billIntegral = memberOrder.getBillIntegral();
            BigDecimal deliverMultiple = memberOrder.getDeliverMultiple();
            BigDecimal multiply = billIntegral.multiply(deliverMultiple);
            BigDecimal forecastSpeedIntegral = memberBillSpeedIntegral.getForecastSpeedIntegral();
            BigDecimal subtract = forecastSpeedIntegral.subtract(multiply);
            memberBillSpeedIntegral.setForecastSpeedIntegral(subtract);
            memberBillSpeedIntegral.setUpdateTime(new Date().getTime());
        }
        memberBillSpeedIntegral.update();
    }
}
//        List<OrderItem> orderItemList = OrderItem.dao.findOrderItemByOrderId(order.getId());
//        for (int i = 0; i < orderItemList.size(); i++) {
//            OrderItem orderItem = orderItemList.get(i);
//            if (orderItem.getItemId() == null) {
//                continue;
//            }
//            Integer itemId = orderItem.getItemId();
//        }
//    }
//            MemberOrderIntegral memberOrderIntegral = MemberOrderIntegral.dao.getMemberOrderByItemId(itemId + "");
//            memberOrderIntegral.setStatus(MemberOrderItergralStatusEnum.CONFIRM_THE_RECEIVE.getCode());
//            memberOrderIntegral.setDeliverMultiple(multiRule);
//            memberOrderIntegral.setUpdateTime(new Date().getTime())

//      设置释放比例,可能（1.5到了3倍，预计可获得积分数,剩余可获得积分数）,积分详情

//        MemberOrderIntegral.dao.get
//          可以直接保存的（留着吧,脑子有点不够用了）
//            BigDecimal integral = BigDecimal.ZERO;
//            if (MemberInfoEnum.FIRST_LEVEL.getCode() == memberInfo.getLevel() || memberInfo.getLevel() == null) {
//                integral = memberBillSpeedIntegral.getNormalIntegral() == null ? integral : memberBillSpeedIntegral.getNormalIntegral();
//                integral = integralIncrement.add(integral);
//                memberBillSpeedIntegral.setNormalIntegral(integral);
//            } else {
//                integral = memberBillSpeedIntegral.getSpeedIntegral() == null ? integral : memberBillSpeedIntegral.getSpeedIntegral();
//                integral = integralIncrement.add(integral);
//                memberBillSpeedIntegral.setSpeedIntegral(integral);
//            }
//            MemberIntegralLog memberIntegralLog = new MemberIntegralLog();
//            memberIntegralLog.setUserIdAndintegralAndIncrementIntegralAndStatusAndCommissionAndReserveAndDesc
//                    (userId, 2, integral, integralIncrement, true, BigDecimal.ZERO,
//                            BigDecimal.ZERO, "购买商品确认收货,增加积分");


//      邀请人分组按照邀请人id,所有会员(求直系子节点个数)
//        InviteeRelative inviteeRelativeByInteviterId = InviteeRelative.dao.getInviteeRelative(userId);
//        if (inviteeRelativeByInteviterId == null || inviteeRelativeByInteviterId.getId() == null) {
//            return;
//        }
//        List<InviteeRelative> dictInviterList = InviteeRelative.dao.findByInviterId(inviteeRelativeByInteviterId.getId());
//        Map<String, InviteeRelative> map = dictInviterList.stream().filter(inviteeRelative -> inviteeRelative.getUserId() != null)
//                .collect(Collectors.toMap(InviteeRelative::getUserId, a -> a, (k1, k2) -> k1));
//        List<MemberInfo> fansMemberList = MemberInfo.dao.memberFankeInfoList(MemberInfoEnum.SECOND_LEVEL.getCode(),
//                MemberInfoEnum.THIRD_LEVEL.getCode());
//        List<MemberInfo> memberInfoList = fansMemberList.stream().filter(fansMember -> fansMember.getUserId() != null
//                && map.containsKey(fansMember.getUserId())).collect(Collectors.toList());
//
//        ReverseMultipleRule reverseMultipleRule = ReverseMultipleRule.dao.getReverse();
//        BigDecimal multiRule = BigDecimal.ZERO;
//        if (memberInfoList.size() == 1 || memberInfoList.size() == 0) {
//            multiRule = reverseMultipleRule.getReverseMultipleCountMin() == null ? BigDecimal.ZERO : reverseMultipleRule.getReverseMultipleCountMin();
//        }
//        if (memberInfoList.size() >= 2) {
//            multiRule = reverseMultipleRule.getReverseMultipleCountMax() == null ? BigDecimal.ZERO : reverseMultipleRule.getReverseMultipleCountMax();
//        }